<?php

namespace App\Jobs;

use App\Models\Shop\WxShopGoods;
use App\Models\Shop\WxShopGoodsProduct;
use App\Models\Shop\WxShopOrderGoods;
use App\Models\Used\WxUsedGood;
use App\Models\WxOrder;
use App\Models\Shop\WxShopOrder;
use App\Wen\Utils\ShopUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class OvertimeOrdersDeleteJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $rows = 0;
        WxShopOrder::where([
            ['status', '=', 0],
            ['pay_status', '=', 1]
        ])->where('created_at', '<', now()->subMinutes(2))->get()->map(function ($v) use (&$rows){
            WxShopOrderGoods::where('order_id', $v->id)->get()->map(function ($v2){
                // 库存返还 $rows = ->delete();
                if($v2->goods_type == 6){
                    // 二手
                    WxUsedGood::where('id', $v2->goods_id)->where('status', 7)->update([
                        'status' => 1
                    ]);
                }else{
                    WxShopGoodsProduct::where('id', $v2->product_id)->where('state', 0)->increment('stock', (int)($v2->quantity));
                }
            });
            WxShopOrder::where('id', $v->id)->delete();
            $rows += 1;
        });
        if($rows > 0){
            _logger_(__file__, __line__, '共清理了'.$rows.'条超时商品订单');
        }



        $rows = WxOrder::where([
            ['order_state', '=', 0],
        ])->where('created_at', '<', now()->subMinutes(2))->delete();
        if($rows > 0){
            _logger_(__file__, __line__, '共清理了'.$rows.'条超时订单');
        }

        // 自动确认收货
        $rows = WxShopOrder::where([
            ['status', '=', 2],
            ['pay_status', '=', 2]
        ])->where('ship_at', '<', now()->subDays(15))->get();
        $deal_rows = 0;
        if($rows->isEmpty()){
        }else{
            $rows->map(function ($v) use (&$deal_rows){
                if(ShopUtils::confirm_recived($v, 0)){
                    $deal_rows += 1;
                }
            });
        }
        if($deal_rows > 0){
            _logger_(__file__, __line__, '自动确认收货：处理了'.$deal_rows.'条已发货订单');
        }

        WxShopGoods::where('state', 1)->where('last_sales_at', '<', current_time())->update(['state'=>0]);

    }
}
